"""
ESP32设备模拟测试脚本
用于测试与图像识别服务器的通信
"""

import requests
import json
import time
import random
import numpy as np
import cv2

# 服务器地址
SERVER_URL = "http://127.0.0.1:5000"

def test_server_status():
    """测试服务器状态"""
    print("测试服务器状态...")
    try:
        response = requests.get(f"{SERVER_URL}/status")
        if response.status_code == 200:
            data = response.json()
            print("✓ 服务器状态正常")
            print(f"  状态: {data['status']}")
            print(f"  病虫害类别: {data['disease_classes']}")
            print(f"  备注: {data['note']}")
            return True
        else:
            print(f"✗ 服务器状态异常: {response.status_code}")
            return False
    except Exception as e:
        print(f"✗ 无法连接到服务器: {e}")
        return False

def generate_test_image():
    """生成测试图像"""
    # 创建一个简单的测试图像
    img = np.zeros((480, 640, 3), dtype=np.uint8)
    
    # 添加一些随机形状来模拟叶片
    for _ in range(5):
        # 随机颜色（绿色系）
        color = (random.randint(0, 50), random.randint(100, 255), random.randint(0, 50))
        
        # 随机位置和大小
        center = (random.randint(50, 590), random.randint(50, 430))
        axes = (random.randint(30, 80), random.randint(30, 80))
        angle = random.randint(0, 360)
        
        # 绘制椭圆
        cv2.ellipse(img, center, axes, angle, 0, 360, color, -1)
    
    # 添加一些斑点来模拟病斑
    if random.random() > 0.5:
        for _ in range(random.randint(1, 10)):
            spot_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
            spot_center = (random.randint(0, 640), random.randint(0, 480))
            spot_radius = random.randint(2, 10)
            cv2.circle(img, spot_center, spot_radius, spot_color, -1)
    
    return img

def test_image_identification():
    """测试图像识别功能"""
    print("\n测试图像识别功能...")
    
    # 生成测试图像
    print("  生成测试图像...")
    img = generate_test_image()
    
    # 将图像编码为JPEG格式
    success, img_encoded = cv2.imencode('.jpg', img)
    if not success:
        print("✗ 图像编码失败")
        return False
    
    # 准备文件数据
    files = {'image': ('test_image.jpg', img_encoded.tobytes(), 'image/jpeg')}
    
    try:
        # 发送图像到服务器
        print("  发送图像到服务器...")
        response = requests.post(f"{SERVER_URL}/identify", files=files)
        
        if response.status_code == 200:
            result = response.json()
            print("✓ 图像识别成功")
            print(f"  识别结果: {result['disease']}")
            print(f"  置信度: {result['confidence']}")
            
            if 'image_info' in result:
                info = result['image_info']
                print(f"  图像信息: {info['width']}x{info['height']}")
                print(f"  清晰度评分: {info['blur_score']:.2f}")
            
            if 'recommendation' in result:
                print(f"  建议: {result['recommendation']}")
                
            return True
        else:
            print(f"✗ 图像识别失败: {response.status_code}")
            print(f"  错误信息: {response.text}")
            return False
            
    except Exception as e:
        print(f"✗ 发送图像时出错: {e}")
        return False

def simulate_sensor_data():
    """模拟传感器数据发送"""
    print("\n模拟传感器数据...")
    
    # 模拟的传感器数据
    sensor_data = {
        "temperature": round(random.uniform(15, 35), 1),
        "humidity": round(random.uniform(30, 80), 1),
        "soil_moisture": random.randint(200, 600),
        "light": random.randint(1000, 15000),
        "co2": random.randint(300, 800)
    }
    
    print("  模拟传感器读数:")
    for key, value in sensor_data.items():
        print(f"    {key}: {value}")
    
    # 在实际应用中，这些数据会通过MQTT发送到服务器
    # 这里我们只是模拟显示
    print("✓ 传感器数据模拟完成")
    return True

def main():
    """主函数"""
    print("ESP32葡萄病虫害监控系统测试脚本")
    print("=" * 40)
    
    # 测试服务器状态
    if not test_server_status():
        return
    
    # 模拟传感器数据
    simulate_sensor_data()
    
    # 测试图像识别功能
    test_image_identification()
    
    print("\n" + "=" * 40)
    print("测试完成!")

if __name__ == "__main__":
    main()